function doPost(req, cb) {
	$.post('/api', JSON.stringify(req), cb, 'json');
}

// Login Button
function login(name, pass, callback) {
	var req = session.command('login', {
		user : {
			name : name,
			password : pass
		}
	});

	doPost(req, function(res) {
		if (res.success) {
			session.set(res.session);
			session.setCookie();
			error.clear();
			callback(true)
		} else {
			session.destroy();
			error.set(res.error);
			callback(false)
		}
	});
};

function logout(callback) {
	var req = session.command('logout');
	doPost(req, function(res) {
		if (res.success) {
			session.destroy();
			error.clear();
			// tracks.reset();
			// view.update(function() {
			callback(true);
			// });
		} else {
			error.set(res.error);
			callback(false);
		}
	});
}

function addTrack(name, location, callback) {
	var req = session.command('addTrack', {
		track : {
			name : name,
			location : location
		}
	});

	doPost(req, function(res) {
		if (res.success) {
			var track = res.track;
			tracks.add(track.id, track);
			callback(true);
		} else {
			error.set(res.error);
			callback(false);
		}
	});
}

function getTracks(callback) {
	var req = session.command('getTracks');
	doPost(req, function(res) {
		if (res.success) {
			tracks.update(res.tracks, function() {
				callback(true);
			});
		} else {
			error.set(res.error);
			callback(false);
		}
	});
}

function updateTrack(id, callback) {
	if (typeof (callback) != 'function') {
		callback = function() {
		};
	}
	var t = tracks.list[id];

	var req = session.command('updateTrack', {
		'track' : {
			id : t.id,
			name : t.name,
			location : t.location,
			points : t.points
		}
	});

	doPost(req, function(res) {
		if (res.success) {
			var updatedTrack = res.track;
			tracks.list[id] = updatedTrack;
			callback(true);
		} else {
			error.set(res.error)
			callback(false);
		}
	});
}

function upload(file, name, callback) {
	var req = session.command('upload', {
		name : name,
		length : file.fileSize
	});
	
	if(file.type != "image/jpeg") {
		error.set({message : "File must be of type img/jpeg!", code : 400});
		callback(false);
		return;
	}

	var reader = new FileReader();
	reader.onload = function(evt) {
		var content = evt.target.result;

		alert(content.length);
		$.post('/upload', JSON.stringify(req) + "\r\n" + content, function(res) {
			if (res.success) {
				callback(true);
			} else {
				error
				callback(false);
			}
		});
	}

	reader.readAsBinaryString(file);
}
